#!/bin/bash

set -e
set -x

# yum -y install --downloadonly --downloaddir=clickhouse-server-rpm clickhouse-server 
bypy download clickhouse-server-rpm.tgz

sh render.sh

iplist_path=config
i=1
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    if [ $address ];then
        sshpass -p$pass scp clickhouse-server-rpm.tgz $address:/opt/
        sshpass -p$pass ssh -n $address tar xf /opt/clickhouse-server-rpm.tgz -C /opt/
        sshpass -p$pass ssh -n $address yum -y --disablerepo='*' localinstall /opt/clickhouse-server-rpm/*.rpm
        cp macros.xml.tpl macros.xml
        shard=$(printf "%02d" "$i")
        sed -i "s/(shard)/$shard/g" macros.xml
        sshpass -p$pass scp macros.xml $address:/etc/clickhouse-server/config.d/macros.xml
        sshpass -p$pass scp cluster.xml $address:/etc/clickhouse-server/config.d/cluster.xml
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl start clickhouse-server
        let i=i+1
    fi
done < $iplist_path

clickhouse-client --query "create database test on cluster cluster1"

set +x
set +e